<template>
  <view>
    <u-popup :show="showWxLogin" mode="bottom" round="44rpx" :closeable="true" @close="onClose">
      <view class="popupBox">
        <view class="h2 bold">获取您的头像、昵称</view>
        <view class="h3">主要用于向用户提供具有辨识度的用户中心界面</view>
        <view class="form">
          <view class="input u-flex">
            <view class="h2">头像</view>
            <view class="info">
              <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="avatar" :src="avatarUrl || '../../../static/head.png'"></image>
              </button>
            </view>
          </view>
          <view class="input u-flex">
            <view class="h2">昵称</view>
            <view class="info2">
              <input type="nickname" v-module="nickName" placeholder="请输入昵称" @blur="onBlur" />
            </view>
          </view>
        </view>
        <view class="submit" :style="{background:PrimaryColor}" @click="submit">确定</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex';
  export default {
    computed: {
      ...mapState(['showWxLogin']),
    },
    data() {
      return {
        PrimaryColor: '#1fba1a', //主题色
        loginType: true,
        avatarUrl: '',
        nickName: ''
      }
    },
    methods: {
      ...mapMutations(['setShowWxLogin', 'setLoginPopupShow']),
      onClose() {
        this.setShowWxLogin(false);
      },
      onChooseAvatar(e) {
        this.avatarUrl = e.detail.avatarUrl;
        getApp().globalData.avatarUrl = e.detail.avatarUrl;
        wx.setStorageSync('avatarUrl', e.detail.avatarUrl);
        console.log('图像地址' + getApp().globalData.avatarUrl);
      },
      onBlur(e) {
        this.nickName = e.detail.value;
        getApp().globalData.nickName = e.detail.nickName;
        wx.setStorageSync('nickName', e.detail.value);
      },
      submit() {
        var that = this
        if (!this.avatarUrl) {
          uni.showToast({
            title: '请上传头像~',
            icon: 'none'
          });
          return
        }
        if (!this.nickName) {
          uni.showToast({
            title: '请输入昵称~',
            icon: 'none'
          });
          return
        }
        uni.getUserProfile({
          desc: '获取您的昵称、头像、地区及性別', //向用户展示的信息
          success: infoRes => {
            uni.login({
              success: function(loginRes) {
                const code = loginRes.code;
                const nickName = wx.getStorageSync('nickName')
                const loginType = true;
                // 缓存用户数据
                wx.setStorageSync('encryptedData', infoRes.encryptedData);
                wx.setStorageSync('iv', infoRes.iv);
                wx.setStorageSync('rawData', infoRes.rawData);
                wx.setStorageSync('signature', infoRes.signature);
                wx.setStorageSync('securityStatus', 1);

                console.log("code：" + code);
                console.log("用户名：" + nickName);
                console.log("登录状态：" + loginType);

                let params = {
                  code: code,
                  userName: nickName,
                };

                uni.request({
                  url: 'http://localhost:8081/user/login/wechat',
                  method: 'POST',
                  header: {
                    "content-type": "application/x-www-form-urlencoded",
                    'Access-Control-Allow-Headers': 'appId',
                    'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
                    'Access-Control-Max-Age': 86400,
                  },
                  data: params,
                  success: (res) => {
                    if (res.statusCode === 200) {
                      console.log("登录成功");
                      console.log(res.data);

                      wx.setStorageSync('sessionID', res.data.data);
                      getApp().globalData.sessionID = res.data.data;
                      // 获取本人详细信息
                      uni.request({
                        url: 'http://localhost:8081/user/of/me',
                        header: {
                          'Access-Control-Allow-Headers': 'appId',
                          'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
                          'Access-Control-Max-Age': 86400,
                          'Authorization': '' + wx.getStorageSync('sessionID')
                        },
                        method: 'GET',
                        success: res => {
                          console.log('获取本人信息成功');
                          console.log(res.data);
                          wx.setStorageSync('myID', res.data.data.id);
                          getApp().globalData.myFansNumber = res.data.data.fans;
                          getApp().globalData.myFollowsNumber = res.data.data.followee;
                          wx.setStorageSync('myFansNumber', res.data.data.fans);
                          wx.setStorageSync('myFollowsNumber', res.data.data.followee);
                        },
                        fail: res => {
                          console.log('获取本人信息失败');
                        }
                      })
                      if (getApp().globalData.loginModal == 0) {
                        uni.switchTab({
                          url: '/pages/main/home'
                        })
                      } else {
                        uni.showToast({
                          title: "登录成功",
                          icon: 'none',
                          duration: 2000
                        })
                      }
                      uni.uploadFile({
                        url: 'http://localhost:8081/upload/blog/' + loginType, // 后端api接口
                        filePath: wx.getStorageSync('avatarUrl'),
                        // uni.chooseImage函数调用后获取的本地文件路劲
                        name: 'file', //后端通过'file'获取上传的文件对象
                        formData: {
                          fileName: wx.getStorageSync('nickName'),
                          // 通过formData传递文件名
                        },
                        header: {
                          "Content-Type": "multipart/form-data",
                          'Access-Control-Allow-Headers': 'appId',
                          'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
                          'Access-Control-Max-Age': 86400,
                          'Authorization': '' + res.data.data
                        },
                        success: (res) => {
                          console.log(res);
                          if (res.statusCode === 200) {
                            console.log('文件上传成功' + res.data);
                          }
                        },
                        fail: (err) => {
                          console.log('文件上传失败' + err.errMsg);
                        }
                      });
                    }
                  },
                  fail: (res) => {
                    console.log("登录失败" + res.errMsg);
                  }
                });
              },
              fail: err => {
                uni.showToast({
                  title: '授权失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            })
          },
          fail: err => {
            uni.showToast({
              title: '授权失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
        this.setShowWxLogin(false);
      },
    },
  }
</script>

<style lang="scss" scoped>
  .popupBox {
    width: 100%;
    padding: 50rpx 40rpx 30rpx;

    .h2 {
      color: #333;
      font-size: 32rpx;
    }

    .h3 {
      font-size: 26rpx;
      color: #999;
      line-height: 1.4;
      padding-top: 14rpx;
    }

    .bold {
      font-weight: bold;
    }

    .form {
      margin-top: 30rpx;
      border-top: 1px solid #EFEFEF;

      .input {
        padding: 24rpx 0;
        border-bottom: 1px solid #EFEFEF;

        .info {
          margin-left: -50rpx;

          .avatar-wrapper {
            width: 100rpx;
            height: 100rpx;

            .avatar {
              position: relative;
              left: -30rpx;
              width: 100rpx;
              height: 100rpx;
            }
          }

        }

        .info2 {
          flex: 1;
          margin-left: 30rpx;

          input {
            background: transparent;
            width: 92%;
            height: 70rpx;
            color: #333;
            font-size: 30rpx;
          }
        }
      }
    }
  }

  .submit {
    margin-top: 30rpx;
    width: 670upx;
    height: 92rpx;
    border-radius: 10rpx;
    text-align: center;
    line-height: 92rpx;
    color: #fff;
    font-size: 32rpx;
    background: #E83F3C;
  }
</style>